package hw03;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class MultivaluedDependency implements Dependency, Comparable<MultivaluedDependency>{

	private Set<Attribute> left;
	private Set<Attribute> right;
	
	public MultivaluedDependency(Set<Attribute> left, Set<Attribute> right) {
		this.left = left;
		this.right = right;
	}

	public MultivaluedDependency(FunctionalDependency F) {
		this.left = new TreeSet<Attribute>(F.getLeft());
		this.right = new TreeSet<Attribute>(F.getRight());
	}
	
	public Set<Attribute> getLeft() {
		return left;
	}
	
	public Set<Attribute> getRight() {
		return right;
	}
	
	@Override
	public String toString() {
		String toString = "";
		Iterator<Attribute> leftIter = new TreeSet<Attribute>(getLeft()).iterator();
		while(leftIter.hasNext()) {
			toString += leftIter.next();
			if(leftIter.hasNext()) {
				toString += ", ";
			}
		}
		toString += " ->> ";
		Iterator<Attribute> rightIter = new TreeSet<Attribute>(getRight()).iterator();
		while(rightIter.hasNext()) {
			toString += rightIter.next();
			if(rightIter.hasNext()) {
				toString += ", ";
			}
		}		
		return toString + ";";
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof FunctionalDependency) {
			FunctionalDependency o = (FunctionalDependency) obj;
			return o.getLeft().equals(o.getLeft()) && getRight().equals(o.getRight());
		}
		return super.equals(obj);
	}

	public static MultivaluedDependency parse(String statement, Schema schema) {
		try {
			String[] components = statement.split("->>");
			Set<Attribute> left = Attribute.parseSet(components[0], schema);					
			Set<Attribute> right = Attribute.parseSet(components[1], schema);
			return new MultivaluedDependency(left, right);
		} catch(Exception e) {}
		return null;
	}

	@Override
	public int compareTo(MultivaluedDependency o) {
		return toString().compareTo(o.toString());
	}
}
